<!DOCTYPE html>
<html>
  <head>
    <title>WebSocket Demo</title>
  </head>
  <body>
    <div id="output"></div>
    <script>
      const ws = new WebSocket(
        "ws://115.234.208.240:5059/websocket?version=18.0-2"
      );

      ws.onopen = function (event) {
        console.log("WebSocket连接已建立");

        // 发送正确格式的订阅消息
        const subscribeMessage = {
          event_name: "subscribe",
          data: {
            channels: ["channel001"],
            last: 0, // 添加必需的 last 参数
          },
        };

        ws.send(JSON.stringify(subscribeMessage));
      };

      ws.onmessage = function (event) {
        console.log("收到消息:", event.data);
        try {
          const data = JSON.parse(event.data);
          console.log("解析后的消息:", data);

          // 处理不同类型的消息
          if (data.type === "typing_message") {
            document.getElementById("output").innerHTML = data.payload.text;
          }
        } catch (e) {
          console.log("非JSON消息:", event.data);
        }
      };

      ws.onerror = function (error) {
        console.error("WebSocket错误:", error);
      };

      ws.onclose = function (event) {
        console.log(
          "WebSocket连接已关闭, 代码:",
          event.code,
          "原因:",
          event.reason
        );
      };
    </script>
  </body>
</html>
